package com.eightbears.beboy.ui.user.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eightbears.beboy.R;
import com.eightbears.beboy.adapter.OrderListAdapter;
import com.eightbears.beboy.base.BaseFragment;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.dialog.CodeDialog;
import com.eightbears.beboy.base.view.qrcode.utils.CodeUtils;
import com.eightbears.beboy.entity.OrderEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.eightbears.beboy.ui.user.activity.OrderDetailActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.PARAMS_PAGE_SIZE;
import static com.eightbears.beboy.base.util.CommonAPI.STATUS_APPLY_REFOUND;
import static com.eightbears.beboy.base.util.CommonAPI.STATUS_UNUSE;
import static com.eightbears.beboy.base.util.CommonAPI.URL_GETSHOPMAELRCODE;
import static com.eightbears.beboy.base.util.CommonAPI.delayMillis;
import static com.eightbears.beboy.ui.user.activity.RefundActivity.EVENT_REFUND;

public class WaitUseOrderFragment extends BaseFragment implements
        BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {

    public static final String PARAMS_ORDER_LIST = "orderList";

    @BindView(R.id.rv_list)
    RecyclerView rv_list;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    @BindView(R.id.view_empty)
    View view_empty;

    private OrderListAdapter orderListAdapter;
    private OrderEntity.OrderInfo orderInfo;
    private CodeDialog.Builder builder;

    private int page = 1;
    private boolean isErr = true;
    private int isEnd = 0;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_wait_user_order, container, false);
        EventBus.getDefault().register(this);
        ButterKnife.bind(this, view);
        initView();
        initData();
        initEvent();
        return view;
    }

    @Override
    protected void initView() {
        initAdapter();
    }

    @Override
    protected void initData() {
        getData();
    }

    @Override
    protected void initEvent() {
        orderListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                orderInfo = (OrderEntity.OrderInfo) adapter.getData().get(position);
                switch (view.getId()) {
                    case R.id.shop_info_meal:
                        startLocalActivity(OrderDetailActivity.class, PARAMS_ORDER_LIST, orderInfo);
                        break;

                    case R.id.tv_shopbook_mealbug:
                        if(builder == null) {
                            String code = "beboy://code/" + orderInfo.getCode();
                            builder = new CodeDialog.Builder(getActivity());
                            builder.setBitmap(CodeUtils.createImage(code, 150, 150, null));
                            builder.setTitle(orderInfo.getCoupon().getTitle());
                            builder.setTv_price("￥" + orderInfo.getCoupon().getPrice());
                            builder.setTv_code(orderInfo.getCode() + "");
                        }
                        builder.create().show();
                        break;

                }
            }
        });
    }

    private void getData() {
        String statusParam = "[" + STATUS_UNUSE + "]";
        swipeLayout.setRefreshing(true);
        OkHttpUtils.get().url(URL_GETSHOPMAELRCODE)
                .addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken())
                .addParams("page", String.valueOf(page))
                .addParams("size", String.valueOf(PARAMS_PAGE_SIZE))
                .addParams("status", statusParam)
                .build().execute(new StringCallback() {

            @Override
            public void onResponse(String response) {
                swipeLayout.setRefreshing(false);
                OrderEntity shopBookEntity = GsonUtil.fromJson(response, OrderEntity.class);
                if (String.valueOf(shopBookEntity.getStatus_code()).equals(CONNECTION_STATUS_SUCCESS)) {
                    isEnd = shopBookEntity.getData().getIs_end();
                    if (page == 1) {
                        if (shopBookEntity.getData().getList().size() == 0) {
                            view_empty.setVisibility(View.VISIBLE);
                        } else {
                            view_empty.setVisibility(View.GONE);
                            orderListAdapter.setNewData(shopBookEntity.getData().getList());
                        }
                    } else {
                        orderListAdapter.addData(shopBookEntity.getData().getList());
                    }
                    orderListAdapter.loadMoreComplete();
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                swipeLayout.setRefreshing(false);
                isErr = false;
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(getActivity(), status_error);
            }
        });
    }

    private void initAdapter() {
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setColorSchemeColors(getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color));
        rv_list.setLayoutManager(new LinearLayoutManager(getActivity()));
        orderListAdapter = new OrderListAdapter();
        orderListAdapter.openLoadAnimation();
        orderListAdapter.setOnLoadMoreListener(this);
        rv_list.setAdapter(orderListAdapter);
    }

    @Override
    public void onRefresh() {
        orderListAdapter.setEnableLoadMore(false);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isErr = true;
                page = 1;
                orderListAdapter.getData().clear();
                getData();
            }
        }, delayMillis);
    }

    @Override
    public void onLoadMoreRequested() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isEnd == 1) {
                    orderListAdapter.loadMoreEnd(true);
                } else {
                    if (isErr) {
                        page++;
                        getData();
                    } else {
                        isErr = true;
                        Toast.makeText(getActivity(), R.string.network_anomalies, Toast.LENGTH_LONG).show();
                        orderListAdapter.loadMoreFail();
                    }
                }
            }
        }, delayMillis);
    }
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onDataSynEvent(String event) {
        switch (event) {
            case EVENT_REFUND:
                orderInfo.setStatus(STATUS_APPLY_REFOUND);
                orderListAdapter.notifyDataSetChanged();
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
